package com.zpark.rabbitmq.work_queue;

import com.rabbitmq.client.*;
import com.zpark.rabbitmq.config.ConnectionUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @PackageName: com.zpark.rabbitmq.work_queue
 * @ClassName: Consumer
 * @Description:
 * @author: RZS
 * @date: 2022/12/13  16:46
 */
public class Consumer {

    private static final String QUEUE_NAME = "work_queue";

    public static void main(String[] args) throws IOException, TimeoutException {
        // 获取连接及通道
        Connection conn = ConnectionUtil.getConnection();
        final Channel channel = conn.createChannel();
        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        // 定义队列的消费者
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "utf-8");
                System.out.println("消费者1，收到消息：msg -> " + msg);
                // 休眠10ms
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        // 监听队列，autoAck为false表示手动返回完成状态，true表示自动
        channel.basicConsume(QUEUE_NAME, true, consumer);
    }
}
